<template>
  <div class="user-management">
    <div class="search-bar">
      <el-input
        placeholder="请输入用户名/手机号"
        v-model="param"
        class="search-input"
      />

      <!-- 状态选择下拉框 -->
      <el-select v-model="status" placeholder="选择状态" class="status-select">
        <el-option label="全部" :value="''"></el-option>
        <el-option label="启用" :value="0"></el-option>
        <el-option label="禁用" :value="1"></el-option>
      </el-select>

      <el-button type="primary" icon="el-icon-search" @click="init">查询</el-button>
      <el-button type="success" @click="addUser">添加管理员</el-button>
    </div>

    <el-table :data="tableData" style="width: 100%" class="user-table">
      <el-table-column prop="id" label="序号" width="80"></el-table-column>
      <el-table-column prop="name" label="用户名" width="180"></el-table-column>
      <el-table-column prop="mobile" label="手机号码" width="180"></el-table-column>
      <el-table-column prop="createtime" label="创建时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.createtime) }}
        </template>
      </el-table-column>
      <el-table-column label="状态" width="120">
        <template #default="{ row }">
          <span>{{ row.status === 0 ? "启用" : "禁用" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="260">
 <template #default="{ row }">
          <el-button-group class="action-btn-group">
            <el-button @click="edit(row)" size="small" class="action-btn">编辑</el-button>
            <el-button
              @click="openResetDialog(row)"
              size="small"
              type="danger"
              class="action-btn"
              >重置密码</el-button>
            <el-button
              @click="setWarehousePermission(row)"
              size="small"
              type="warning"
              class="action-btn"
              >仓库权限</el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      :current-page="page"
      :page-size="pageSize"
      :total="total"
      @current-change="handleCurrentChange"
      layout="prev, pager, next, jumper, ->, total"
      class="pagination"
    />
    <!-- 重置密码弹窗 -->
    <el-dialog v-model="resetDialogVisible" title="重置密码" width="300px">
      <span>确定要重置该管理员密码吗？</span>
      <template #footer>
        <el-button @click="resetDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmResetPassword">确定</el-button>
      </template>
    </el-dialog>
    <adminForm v-if="showForm" :row="editRow" :type="editRow ? 'edit' : 'add'" @close="showForm = false" />
  </div>
</template>

<script setup>
import {useRouter} from "vue-router";
import { ElMessage } from "element-plus";
import { ref, onMounted } from "vue";
import {queryAdmin,setPassword} from "@/api/set/keeper.js"
import adminForm from "./son/adminForm.vue";
const router = useRouter();
// 数据初始化
const tableData = ref([]);
const page = ref(1);
const pageSize = ref(4);
const total = ref(0);
const param = ref(""); // 用户名/手机号
const status = ref(""); // 状态过滤条件
const showForm = ref(false);
const editRow = ref(null);
// 重置密码弹窗控制
const resetDialogVisible = ref(false);
const resetRow = ref(null);


// 打开弹窗
const openResetDialog = (row) => {
  resetRow.value = row;
  resetDialogVisible.value = true;
};

// 确认重置密码
const confirmResetPassword = async () => {
  try {
    // 调用重置密码接口
    const res = await setPassword(resetRow.value.id);
    resetDialogVisible.value = false;
    if (res.code === 200) {
      ElMessage.success("重置密码成功！");
      init(); // 刷新数据
    } else {
      ElMessage.error("重置密码失败：" + (res.msg || ""));
    }
  } catch (e) {
    resetDialogVisible.value = false;
    ElMessage.error("重置密码失败！");
  }
};

// 格式化日期
function formatDate(dateStr) {
  if (!dateStr) return "";
  return dateStr.replace("T", " ").slice(0, 16);
}

// 查询数据
async function init() {
    let queryParams = {
        page: page.value,
        pageSize: pageSize.value
    };
     if (param.value && param.value.trim() !== "") {
        queryParams.param = param.value.trim();
    }
    if (status.value !== "" && status.value !== null && status.value !== undefined) {
        queryParams.status = status.value;
    }
    console.log('查询参数:', queryParams);
    let res = await queryAdmin(queryParams);
    console.log('接口返回：', res);
    if(res.code==200){
        tableData.value = res.data.list;
        total.value = res.data.total;
        console.log("管理员数据:", JSON.parse(JSON.stringify(tableData.value)));
    }
}

//生命周期函数调用初始化方法
onMounted(() => {
    init();
});

// 处理分页变化
const handleCurrentChange = (newPage) => {
  page.value = newPage;
  init();
};


// 仓库权限
const setWarehousePermission = (row) => {
  console.log("设置仓库权限:", row);
router.push({
  name: "仓库权限",
  query: {
    id: row.id,
    name: row.name,
    phone: row.mobile,
  },
});
};
// 新增管理员
const addUser = () => {
  router.push({ path: '/set/keeper/form', query: { type: 'add' } });
};

// 编辑管理员
const edit = (row) => {
localStorage.setItem('editRow', JSON.stringify(row));
  router.push({
    path: '/set/keeper/form',
    query: { type: 'edit', id: row.id }
  });
};



</script>

<style scoped>
.user-management {
  margin: 20px;
}

.search-bar {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding: 10px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.search-input {
  margin-right: 10px;
  width: 250px;                                  
}

.status-select {
  margin-left: 10px;
  width: 150px;
}

.el-button {
  margin-left: 10px;
}

.user-table {
  background-color: #fff;
  border-radius: 6px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.el-table th {
  background-color: #f5f7fa;
  color: #333;
  font-weight: bold;
}

.el-table-column {
  text-align: center;
}

.el-button {
  font-size: 14px;
  padding: 6px 12px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.action-btn-group {
  display: flex;
  justify-content: center; /* 可改为flex-start左对齐 */
  align-items: center;
  gap: 8px;
}

.action-btn {
  min-width: 70px;
  flex: 1 1 0;
  text-align: center;
  padding: 6px 0;
}
</style>
